package net.da;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

/*
 * This class should be refactored earlier when it'll be clear what
 * we need from injection initialization.
 */
public class DaStarter {

	private static Injector injector;

	private static boolean PRODUCTION_CONFIGURATION = false;
	private static final String PRODUCTION_INJECTION_CONFIGURATION = "net.da.ProductionInjectionConfiguration";
	private static final String TEST_INJECTION_CONFIGURATION = "net.da.TestInjectionConfiguration";


	/*
	 * Please, use this method as rear as possible.
	 */
	public static Injector getInjector() {
		if (injector == null) {
			AbstractModule injectionConf = resolveInjectionConfiguration();
			injector = Guice.createInjector(injectionConf);
		}
		return injector;
	}

	private static AbstractModule resolveInjectionConfiguration() {

		Class<?> clazz;
		AbstractModule abstractModule;
		try {
			if (PRODUCTION_CONFIGURATION) {
				clazz = Class.forName(PRODUCTION_INJECTION_CONFIGURATION);				
			} else {
				clazz = Class.forName(TEST_INJECTION_CONFIGURATION);
			}
		} catch (ClassNotFoundException e) {
			throw new IllegalStateException(e);
		}
		try {
			abstractModule = (AbstractModule) clazz.newInstance();
		} catch (InstantiationException e) {
			throw new IllegalStateException(e);			
		} catch (IllegalAccessException e) {
			throw new IllegalStateException(e);
		}		
		return abstractModule;

	}

}
